package cn.edu.huanu.dao.impl;

import cn.edu.huanu.dao.BookDao;
import cn.edu.huanu.exception.DaoException;
import cn.edu.huanu.pojo.Book;
import cn.edu.huanu.utils.ConnectionUtils;
import cn.edu.huanu.utils.RowMapper;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hb
 * @date 2025-11-14 10:00:28
 */
public class BookDaoImpl implements BookDao {

    @Override
    public List<Book> queryBookByPageOrderByPubDate(int beginIndex, int offset) throws DaoException {
        final String sql = "SELECT t.id,title,author,publisher,price,FORMAT,paper,packing,isbn,pic,cid,isonline,pubdate,content "
                + "FROM t_book t,t_book_content b WHERE t.id=b.bid and content is not null ORDER BY pubdate DESC LIMIT ?,?";

        return ConnectionUtils.query(sql,  (rs)-> {
                List<Book> books = new ArrayList<>();
                while (rs.next()) {
                    books.add(parseResultSet(rs));
                }
                return books;
        }, beginIndex, offset);

    }

    @Override
    public Book queryBookById(Integer id) throws DaoException {
        final String sql = "SELECT t.id,title,author,publisher,price,FORMAT,paper,packing,isbn,pic,cid,isonline,pubdate,content "
                + "FROM t_book t,t_book_content b WHERE t.id=b.bid and t.id=?";

        return ConnectionUtils.query(sql,  (rs)-> {
            Book book = null;
            if (rs.next()) {
               book=parseResultSet(rs);
            }
            return book;
        }, id);
    }

    private Book parseResultSet(ResultSet rs) throws Exception {
        Book b = new Book();
        b.setId(rs.getInt("id"));
        b.setTitle(rs.getString("title"));
        b.setAuthor(rs.getString("author"));
        b.setPublisher(rs.getString("publisher"));
        b.setPrice(rs.getDouble("price"));
        b.setFormat(rs.getString("format"));
        b.setPaper(rs.getString("paper"));
        b.setPacking(rs.getString("packing"));
        b.setIsbn(rs.getString("isbn"));
        b.setPic(rs.getString("pic"));
        b.setCid(rs.getInt("cid"));
        b.setIsonline(rs.getBoolean("isonline"));
        b.setPubdate(rs.getDate("pubdate").toLocalDate());
        b.setContent(rs.getString("content"));
        return b;
    }
}
